package com.securinets.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

import com.securinets.news.Article;

public class   ClientJSON {

	private static final String LOG_TAG = "ClientJSON";
	private static final String NOM_HOTE_SECURINES = "http://10.0.2.2/Securinets";
	//private static final String PATH_METHODE = "/android.php";
//	private static final String PARAMETRES_REQUETE_JSON = "";
	
	

	public static ArrayList<Article> resultatsSecurinetsJSON(String PATH_METHODE) {
		HttpClient httpClient = new DefaultHttpClient();
		ArrayList<Article> articles = null;
		try {
			HttpGet httpGet = new HttpGet(NOM_HOTE_SECURINES+PATH_METHODE);
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				InputStream inputStream = httpEntity.getContent();
				// Lecture du retour au format JSON
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(inputStream));
				StringBuilder stringBuilder = new StringBuilder();
				String ligneLue = bufferedReader.readLine();
				while (ligneLue != null) {
					stringBuilder.append(ligneLue + "\n");
					ligneLue = bufferedReader.readLine();
				}
				bufferedReader.close();
				// Analyse du retour
				
				articles = new ArrayList<Article>();
				Log.i(LOG_TAG, stringBuilder.toString());
				JSONArray jsonArray = new JSONArray(stringBuilder.toString());
				for (int i = 0; i < jsonArray.length(); i++) {
					articles.add(new Article("",jsonArray.getJSONObject(i).getString("titre") , jsonArray.getJSONObject(i).getString("desc")));	
				}	
				
			}
			
			
		} catch (IOException e) {
			Log.e(LOG_TAG, e.getMessage());
		} catch (JSONException e) {
			Log.e(LOG_TAG, e.getMessage());
		}
		
		return articles;
	}
}
